package com.raychi.demo.servlet.product;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.raychi.demo.entity.Product;
import com.raychi.demo.util.JdbcUtil;
import com.raychi.demo.util.ProductUtil;

public class ProductServlet  extends HttpServlet{

	private static final long serialVersionUID = 1L;
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			List<Product> list = getProducts();
			request.setAttribute("list", list);
			request.getRequestDispatcher("/indexProduct.jsp").forward(request, response);
		} catch (ClassNotFoundException | SQLException e) {
		
			e.printStackTrace();
		}
		
	}
	private List<Product> getProducts() throws ClassNotFoundException, SQLException{
		List<Product> products = new ArrayList<Product>();
		Connection conn = JdbcUtil.getConnection();
		Statement st = conn.createStatement();
		ResultSet rs = st.executeQuery("select * from product");
		Product product = null;
		while(rs.next()){
			product = ProductUtil.createProduct(rs);
			products.add(product);
		}
				
		return products;
	}

}
